<template>
  <div id='building'>
    <div class="login-box" >
      <div class="title"><h1 class="t1"><b>今日头条</b></h1></div>
       <div class="form">
          <el-form :model="LoginUser" :rules="rules" status-icon ref="ruleForm" class="demo-ruleForm" style="width: 300px;">
            <!-- <el-form-item prop="id">
              <el-input prefix-icon="el-icon-s-custom" placeholder="请输入登录ID" v-model="LoginUser.id"></el-input>
            </el-form-item> -->
            <el-form-item prop="name">
              <el-input prefix-icon="el-icon-s-custom" placeholder="请输入登录账号" v-model="LoginUser.name"></el-input>
            </el-form-item>
            <el-form-item prop="pass">
              <el-input prefix-icon="el-icon-view" type="password" placeholder="请输入登录密码" v-model="LoginUser.pass"></el-input>
            </el-form-item>
             <div id="canvas-input">
                <el-input class="canvas-input-class" type='text' v-model="value" placeholder="请输入算数结果" />
                <canvas id="canvas" @click="dj" style="border: 1px solid #ccc"></canvas>
            </div>
            <el-form-item>
              <el-button size="medium" type="primary" @click="Login" style="width: 100%">登录</el-button>
            </el-form-item>
            
          </el-form>
         
        </div>
        <div style="height: 25px;">
          没有账号？立即前往<router-link to="/register" >[注册]</router-link>

        </div>
        <div>
        <el-button type="text" @click="gotoHomePage()">以游客身份进入></el-button>
        </div>
        <div class="under">
          <img class="under-img" src="../assets//imgs/under.jpg">
        </div>
    </div>
 
</div>
</template>
<script>
import { mapActions } from "vuex";
import { mapState} from "vuex";


export default {
    name: "MyLogin",
    data() {

        let validateName = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("请输入用户名"));
            }
            else {
                return callback();
            }
        };
        // 密码的校验方法
        let validatePass = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("请输入密码"));
            }
            else {
                return callback();
            }
        };
        return {
            LoginUser: {
              //  id:"",
                name: "",
                pass: "", },
                // 验证码
                show_num: [],
                 value: '',
           
            // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
            rules: {
               // id: [{ validator: validateId, trigger: "blur" }],
                name: [{ validator: validateName, trigger: "blur" }],
                pass: [{ validator: validatePass, trigger: "blur" }],
            },
            userinfo:{
           
                id: "",
                username: " ",
                sex: " ",
                avtar: " ",
                telnumber: 0,
                email: null,
                brith: null,
                introduce:""
           }
            
     
        };
    },
    created(){
        // this.getCode();
    },
    mounted() {
        this.show_num=[];
        this.draw();
    },

    methods: {
        ...mapState(["userName"]),
        ...mapActions(["setuserId", "setuserName", "setuserClass","getuserName"]),
        sublim() {
            let [num1=0, type, num2=0] = this.show_num||[];
            let NUM_MAP = {
                '+': num1+num2,
                '-': num1-num2,
                '*': num1*num2
            }
            if(!this.value) return alert('请输入验证码！');
            if(this.value == NUM_MAP[type]){
            
                this.dj()
                this.getavtar();
                this.notifySucceed("登录成功");  
                this.gotoHomePage();
                            
            }else{
                alert('验证码错误！\n你输入的是:  '+this.value+"\n正确的是:  "+NUM_MAP[type]+'\n请重新输入！');
                this.dj()
            }
        },
        // 随机颜色
        randomColor() {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            return "rgb(" + r + "," + g + "," + b + ")";
        },
        // 绘制干扰（线条，原点）
        drawLine(context, canvas_width, canvas_height) {
            for (var i = 0; i <= 5; i++) { //验证码上显示线条
                context.strokeStyle = this.randomColor();
                context.beginPath();
                context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
                context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
                context.stroke();
            }
            for (var j = 0; j <= 30; j++) { //验证码上显示小点
                context.strokeStyle = this.randomColor();
                context.beginPath();
                var x = Math.random() * canvas_width;
                var y = Math.random() * canvas_height;
                context.moveTo(x, y);
                context.lineTo(x + 1, y + 1);
                context.stroke();
            }
        },
        // 绘制单个字符
        drawStr(context, txt, x) {
            var y = 80 + Math.random() * 8;//文字在canvas上的y坐标（20+0到8的随机数）
            context.font = "bold 60px 微软雅黑";
 
            context.fillStyle = this.randomColor(); // 随机生成一个颜色
            context.fillText(txt, x, y);
            return x + 20 + context.measureText(txt).width; //宽度
        },
        drawNum(context, randomList, currentWidth) {
            var j = Math.floor(Math.random() * randomList.length);//获取到随机的索引值 Math.floor(Math.random()*(max-min+1)+min);
            var txt = randomList[j];//得到随机的一个内容
            this.show_num.push(txt);
            return this.drawStr(context, txt, currentWidth);
        },
        draw(codeLength=3) { // codeLength: 设置验证码长度
            let canvas = document.getElementById("canvas");//获取到canvas的对象，演员
            let context = canvas.getContext("2d");//获取到canvas画图的环境，演员表演的舞台
            let canvas_width=canvas.width;
            let canvas_height=canvas.height;
            context.clearRect(0,0, canvas_width, canvas_height);
            console.log(codeLength);
            this.show_num=[];
            let currentWidth=0;
            // 数字一
            currentWidth = this.drawNum(context, new Array(100).fill(null).map((v, i) => i), currentWidth);
            // 运算类型
            currentWidth = this.drawNum(context, ['+', '-', '*'], currentWidth);
            // 数字二
            currentWidth = this.drawNum(context, new Array(10).fill(null).map((v, i) => i), currentWidth);
            // 绘制= ?
            this.drawStr(context, '= ?', currentWidth)
            // 一些干扰因素（线条，原点）
            this.drawLine(context, canvas_width, canvas_height); 
        },
        
        dj() {
            this.value=''
            this.draw();   
        },
    
   // 登录
        Login() {
            // 通过element自定义表单校验规则，校验用户输入的用户信息
            this.$refs["ruleForm"].validate((valid) => {
                //如果通过校验开始登录
                if (valid) {
                    this.$axios
                        .get(`/api/login?user_name=${this.LoginUser.name}&user_password=${this.LoginUser.pass}`)
                        .then((res) => {
                        console.log(res);
                        let user = JSON.stringify(res.data);
                        let t = Number(user);
                        if (t == -1) {
                            this.$refs["ruleForm"].resetFields();
                            alert("账号未注册");
                        }
                        else if (t == -2) {
                            this.$refs["ruleForm"].resetFields();
                            alert("密码错误");
                        }
                        else {
                            user=user.substring(1,user.length-1);
                            let info=user.split(",");
                            this.$store.dispatch("setuserId",info[0]);
                            this.$store.dispatch("setuserName",info[1]);
                            this.$store.dispatch("setuserClass",info[2]);
                            this.$store.dispatch("setIsLogin",true);           
                            localStorage.setItem("IsLogin",true);
                            
                            localStorage.setItem("userId", info[0]);
                            localStorage.setItem("userName", info[1]);
                            localStorage.setItem("userClass", info[2]);
                            console.log(this.$store.getters.getuserName);
                            console.log(localStorage.getItem("IsLogin"));
                            this.sublim();
                            
                        }
                    })
                        .catch((err) => {
                        console.warn(err);
                    });
                }
                else {
                    return false;
                }
            });
        },
        getavtar()
        {
            this.$axios
                        .get(`/api/userinfo?id=${localStorage.getItem("userId")}`)
                        .then((res) => {
                        console.log(res.data); 
                        this.userinfo=res.data; 
                        localStorage.setItem("Info",this.userinfo)
                        if(this.userinfo.avtar!=null)  
                            localStorage.setItem("avtar",this.userinfo.avtar);
                        else
                            localStorage.setItem("avtar","https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png");
                        console.log(localStorage.getItem("avtar"));
                            
                        
                    })
                        .catch((err) => {
                        console.warn(err);
                    });
        },
        gotoHomePage()
        {
            this.$router.push('/homepage')
        },

       
    },
    // components: { route }
};
</script>
<style >
 #building{
  background:url("../assets/imgs/login.png");
  width:100%;
  height:100%;
  position:fixed;
  background-size:100% 100%;
}
.login-box {
    width: 400px;
    height: 550px;
    background-color: #fff;
    border-radius: 3px;
    position: relative;
    left: 10%;
    top: 20%;
    opacity: 0.8;
    border-radius: 15px;

}
.form{
  width: 300px;
 padding:50px;
 padding-top: 0px;
 padding-bottom: 0px;
   
}
.title
{
  padding: 25px;
  padding-bottom: 15px;
}
.under{
  position: absolute;
  width:400px;
  height:100px;
  bottom: 0;
 
  
}
.under-img{
    width: 400px;
    height: auto;  
    max-width: 100%;  
    max-height: 100%;   
   border-bottom-left-radius:15px;
   border-bottom-right-radius:15px;
   padding-top: 5px;
}
.t1{
    font: 36px "微软雅黑"; /*设置字体和字体大小*/
	margin:20px auto; /*设置元素外边距*/
	font-weight: 300; /*设置字体粗细*/
	text-align: center; /*设置文字居中*/
	color: #1f78d8; /*设置文字颜色*/
  letter-spacing: 0.2em;/*设置文字间距*/ 
  -webkit-animation:bounce 2s infinite;/*设置动画*/
	}
@-webkit-keyframes bounce{/*创建动画*/
     0%,100%,20%,50%,80%{ -webkit-transform:translateY(0);}
     40%{-webkit-transform:translateY(-30px);}
     60%{-webkit-transform:translateY(-15px);}
	}
#canvas-input{
    display: flex;
    height: 40px;
    margin-bottom: 10px;
}
.canvas-input-class{
    flex: 3;
    margin-right: 10px;
}
#canvas{
    flex:3;
}
</style>
